package data_structure;

import java.util.LinkedList;
import java.util.List;

public class leetcode_0637 {
    public List<Double> averageOfLevels(TreeNode root) {
        LinkedList<TreeNode> queue=new LinkedList<>();
        LinkedList<Integer> num=new LinkedList<>();
        List<Double> result=new LinkedList<>();
        if(root==null) return result;
        queue.add(root);
        num.add(0);
        Double sum= (double) root.val;
        int current=0;
        int time=1;
        while(!queue.isEmpty()){
            TreeNode node=queue.getFirst();
            queue.removeFirst();
            int number=num.getFirst();
            num.removeFirst();
            if(node.left!=null) {
                queue.add(node.left);
                num.add(number + 1);
            }
            if(node.right!=null){
                queue.add(node.right);
                num.add(number + 1);
            }
            if(number==current){
                sum+=node.val;
                time++;
            }
            else{
                result.add(sum/time);
                sum=(double)node.val;
                current=number;
                time=1;
            }
        }
        result.add(sum/time);
        return result;
    }
}
